<template>
  <div>
    <el-row class="search-area">
      <el-input
        class="search-input"
        v-model.trim="realTimeKeyword"
        placeholder="请输入搜索内容"
        size="medium"
        @keyup.enter.native="search"
        clearable
      ></el-input>
      <el-button type="primary" size="default" @click="search">搜索</el-button>
    </el-row>
    <div class="serve-list">
      <el-row>
        <el-col :span="7" :offset="1">
          <el-tabs
            v-model="statusFilter"
            :stretch="true"
            @tab-click="handleClick"
            class="tab_change"
          >
            <el-tab-pane label="所有问卷" name="all"></el-tab-pane>
            <el-tab-pane label="已开启" name="已开启"></el-tab-pane>
            <el-tab-pane label="已关闭" name="已关闭"></el-tab-pane>
            <el-tab-pane label="未发布" name="未发布"></el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="12" :offset="-5" style="float: right">
          <el-select v-model="order" placeholder="时间排序">
            <el-option
              v-for="item in orderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <div
        v-for="survey in surveysToDisplay"
        :key="survey.sid"
        class="serve-item"
        :id="survey.sid"
      >
        <div class="item-top">
          <div class="item-left item-title">{{ survey.title }}</div>
          <div class="item-info">创建时间: {{ survey.creTime }}&nbsp;</div>
          <div class="item-info">答卷数: {{ survey.ansNum }}&nbsp;&nbsp;</div>
          <div class="item-info">状态: {{ survey.status }}&nbsp;&nbsp;</div>
          <!-- <div class="item-info">ID：{{ survey.sid }}</div> -->
        </div>
        <hr />
        <div class="item-bottom">
          <div class="item-left">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="editSurvey(survey)"
              >编辑问卷</el-button
            >
            <el-button
              type="text"
              icon="el-icon-share"
              @click="shareSurvey(survey)"
              >分享问卷</el-button
            >
            <el-button
              type="text"
              icon="el-icon-s-data"
              @click="analyzeSurvey(survey)"
              >统计&分析</el-button
            >
          </div>
          <div class="item-right">
            <el-button
              type="primary"
              icon="el-icon-delete"
              @click="delSurvey(survey)"
              >删除</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-document-copy"
              @click="copySurvey(survey)"
              >复制</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-video-pause"
              v-if="survey.status === '已开启'"
              @click="closeSurvey(survey)"
              >关闭</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-video-play"
              v-else
              @click="openSurvey(survey)"
              >开启</el-button
            >
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="发布设置" :visible.sync="isPublishing">
      <div>
        <span>定时发布(默认为立即发布):</span><br /><el-date-picker
          v-model="pubTime_datetime"
          type="datetime"
          placeholder="选择日期时间"
        >
        </el-date-picker>
      </div>
      <div style="margin-top: 20px">
        <span>截止时间(默认为无截止时间):</span><br /><el-date-picker
          v-model="deadline_datetime"
          type="datetime"
          placeholder="选择日期时间"
        >
        </el-date-picker>
      </div>
      <div style="margin-top: 20px">
        <span>问卷口令(默认为无需口令):</span>
        <el-input
          placeholder="输入问卷口令..."
          v-model="surveyCode"
          prefix-icon="el-icon-lock"
        ></el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="confirmPublish" type="primary">确认发布</el-button>
        <el-button @click="isPublishing = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="分享问卷链接"
      :visible.sync="isSharing"
      :close-on-click-modal="false"
      :show-close="false"
      :close-on-press-escape="false"
    >
      <div style="font-size: 25px" class="link">
        问卷链接 :
        <el-input
          v-model="shareLink"
          style="
            width: 300px;
            border: 1px solid #dcdfe6;
            font-size: 18px;
            border-radius: 5px;
          "
        ></el-input
        ><el-button @click="copy">复 制</el-button>
        <el-button @click="open_survey">打 开</el-button>
      </div>
      <div style="font-size: 25px">二维码 :</div>
      <div style="text-align: center">
        <vue-qr :text="shareLink" :size="200" :margin="10"></vue-qr>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="back" type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="编辑警告"
      :visible.sync="isEditing"
      :close-on-click-modal="false"
      :show-close="false"
      :close-on-press-escape="false"
    >
      <div style="font-size: 25px" class="link">
        编辑问卷将会清空原有的答卷，确定要继续吗？
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="confirmEdit" type="primary">确 认</el-button>
        <el-button @click="isEditing = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      surveyToAnalyze: {
        sid: "",
        ansNum: 10,
        questions: [],
      }, // 请求得到的问卷结果数据
      deadline_datetime: '',
      pubTime_datetime: '',
      surveyCode: "",
      isPublishing: false,
      sidToPub: "",
      isSharing: false,
      isSharingExam: false,
      surveySidToShare: "",
      isEditing: false,
      surveyToEdit: {},
      List1: [],
      List2: [],
      statusFilter: "all",
      orderOptions: [
        {
          value: "time-reverse",
          label: "时间倒序",
        },
        {
          value: "time-sequential",
          label: "时间正序",
        },
        {
          value: "ansNum-sequential",
          label: "答卷数升序",
        },
        {
          value: "ansNum-reverse",
          label: "答卷数降序",
        },
      ],
      value: "",
      keyword: "",
      realTimeKeyword: "",
      order: "time-reverse",
      surveys: [
        //
        // {
        //   sid: "99999",
        //   title: "wwwww",
        //   ansNum: "90",
        //   creTime: "2008-01-03",
        //   pubTime: "2000-01-01",
        //   deadline: "2024-01-01",
        //   status: "open",
        // },
      ],
      aSurvey: {
        // author: null,
        // title: "测试问卷",
        // description: "这是描述",
        // creTime: 1629539507000,
        // pubTime: 1629539626000,
        // deadline: 1630403611000,
        // status: 1,
        // ansNum: 0,
        // questions: [
        //   {
        //     type: 0,
        //     stem: "你是谁?",
        //     isRequired: true,
        //     propJson: {
        //       options: ["选项一123", "选项二456", "新增选项789"],
        //       num: [0, 0, 0],
        //     },
        //   },
        // ],
      },
    };
  },
  methods: {
    handleClick(tab, event) {
      // console.log(tab, event);
      // console.log(this.statusFilter);
    },
    search() {
      this.keyword = this.realTimeKeyword;
      // alert(`realTimeKeyword: ${this.realTimeKeyword}\nkeyword: ${this.keyword}`);
    },
    copy() {
      var cInput = document.createElement("input");
      cInput.value = this.shareLink;
      document.body.appendChild(cInput);
      cInput.select(); // 选取文本框内容
      // 执行浏览器复制命令
      // 复制命令会将当前选中的内容复制到剪切板中（这里就是创建的input标签）
      // Input要在正常的编辑状态下原生复制方法才会生效
      document.execCommand("copy");
      this.$message({
        type: "success",
        message: "复制成功",
      });
      document.body.removeChild(cInput);
    },
    open_survey() {
      window.open(this.shareLink, "_blank");
    },
    back() {
      this.isSharing = false;
    },
    editSurvey(survey) {
      this.surveyToEdit = survey
      if (survey.ansNum != 0) {
        this.isEditing = true
      } else {
        this.confirmEdit()
      }
    },
    confirmEdit() {
      let survey = this.surveyToEdit
      let vm = this;
      let sidToEdit = survey.sid;
      if (sidToEdit.length === 0) {
        this.$message("网页错误，请刷新页面后再次尝试");
        return;
      }
      this.$http
        .get("/survey/" + sidToEdit)
        .then((res) => {
          if (res.status === 200) {
            this.$message("成功获取问卷信息");
            this.aSurvey = JSON.parse(JSON.stringify(res.data));
            this.aSurvey.questions.forEach((q) => {
              q.propJson = JSON.parse(q.propJson);
            });
            this.aSurvey["sid"] = sidToEdit;
            console.log(this.aSurvey);
            console.log("above is parsed, now commiting...");
            this.$store.commit("continue", this.aSurvey);
            this.$router.push(
              this.aSurvey.type === 0 ? "create_normal" : "create_exam"
            );
          }
        })
        .catch(function (err) {
          console.log(err);
          vm.$message("网络错误");
        });
    },
    delSurvey(survey) {
      let vm = this;
      let sidToDel = survey.sid;
      if (sidToDel.length === 0) {
        this.$message("网页错误，请刷新页面后再次尝试");
        return;
      }
      this.$http
        .put("/survey/status?sid=" + sidToDel + "&status=Deleted")
        .then((res) => {
          if (res.status === 200) {
            // console.log("更新前");
            this.surveys.splice(this.surveys.indexOf(survey), 1);
            // vm.$router.go(0);
            // console.log("更新完了");
            this.$message("删除成功");
          }
        })
        .catch((err) => {
          if (err.response.status === 401) {
            this.$message("用户未登录");
          } else if (err.response.status === 500) {
            this.$message("服务器错误");
          } else {
            this.$message.error("网络错误，请稍后再试！");
          }
        });
    },
    openSurvey(survey) {
      this.sidToPub = survey.sid;
      if (this.sidToPub.length === 0) {
        this.$message("网页错误，请刷新页面后再次尝试");
        return;
      } else {
        // console.log(this.sidToPub);
        this.isPublishing = true;
      }
    },
    confirmPublish() {
      let vm = this;
      this.$http
        .put(
          "/survey/status?sid=" +
            this.sidToPub +
            "&status=Open" +
            (this.isEmptyString(this.surveyCode)
              ? ""
              : "&code=" + this.surveyCode) +
            (this.isEmptyString(this.pubTime_datetime)
              ? ""
              : "&pubTime=" + Date.parse(this.pubTime_datetime)) +
            (this.isEmptyString(this.deadline_datetime)
              ? ""
              : "&deadline=" + Date.parse(this.deadline_datetime))
        )
        .then((res) => {
          if (res.status === 200) {
            let surveyToPub = this.surveys.filter(function (s) {
              return s.sid === vm.sidToPub;
            })[0];
            surveyToPub.status = "已开启";
            this.$message("发布成功");
            // this.$router.go(0);
          }
          this.isPublishing = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    closeSurvey(survey) {
      let vm = this;
      this.$http
        .put("/survey/status?sid=" + survey.sid + "&status=Closed")
        .then((res) => {
          if (res.status === 200) {
            survey.status = "已关闭";
            this.$message("关闭成功");
            // vm.$router.go(0);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    copySurvey(survey) {
      let surveySidToCopy = survey.sid;
      if (surveySidToCopy.length === 0) {
        this.$message("网页错误，请刷新页面后再次尝试");
        return;
      }
      // console.log("copy");
      let vm = this;
      this.$http
        .post("/survey/copy" + "?sid=" + surveySidToCopy)
        .then(function (res) {
          if (res.status === 200) {
            vm.$message("复制成功");
            // console.log("更新前");
            vm.$router.go(0);
            // console.log("更新完了");
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    shareSurvey(survey) {
      this.surveySidToShare = survey.sid;
      if (this.surveySidToShare.length === 0) {
        this.$message("网页错误，请刷新页面后再次尝试");
      } else {
        // console.log(this.surveySidToShare);
        this.isSharing = true;
        this.isSharingExam = survey.type === 1;
      }
    },
    analyzeSurvey(survey) {
      // TODO 先获取要分析的问卷数据
      this.$http.get("/stat/survey/" + survey.sid).then((res) => {
        if (res.status === 200) {
          this.surveyToAnalyze = JSON.parse(JSON.stringify(res.data));
          this.surveyToAnalyze["sid"] = survey.sid;
          console.log(this.surveyToAnalyze);
          console.log(
            "above: parsed surveyToAnalyze object, committing to vuex now"
          );
          this.$store.commit("saveSurveyAnalysis", this.surveyToAnalyze);
          this.$router.push("report");
        }
      });
    },
    webPrint() {
      let url = "www.baidu.com";
      window.open(url, "print_iframe");
      document.getElementById("print_iframe").style.display = "block";
      window.print();
    },
    copy() {
      var cInput = document.createElement("input");
      cInput.value = this.shareLink;
      document.body.appendChild(cInput);
      cInput.select(); // 选取文本框内容
      // 执行浏览器复制命令
      // 复制命令会将当前选中的内容复制到剪切板中（这里就是创建的input标签）
      // Input要在正常的编辑状态下原生复制方法才会生效
      document.execCommand("copy");
      this.$message({
        type: "success",
        message: "复制成功",
      });
      document.body.removeChild(cInput);
    },
    open_survey() {
      window.open(this.shareLink, "_blank");
    },
    isEmptyString(obj) {
      if (
        typeof obj == "undefined" ||
        obj == null ||
        obj == "" ||
        obj == "NaN" ||
        obj == NaN
      ) {
        return true;
      } else {
        return false;
      }
    },
  },
  computed: {
    shareLink() {
      return (
        "http://106.12.141.103:8080/index.html#/" +
        (this.isSharingExam ? "exam" : "question") +
        "/" +
        this.surveySidToShare
      );
    },
    surveysToDisplay() {
      var vm = this;
      return this.surveys
        .filter(function (s) {
          //按状态筛选
          return vm.statusFilter === "all"
            ? true
            : s.status === vm.statusFilter;
        })
        .filter(function (s) {
          //按关键词搜索
          return vm.keyword.length === 0 ? true : s.title.includes(vm.keyword);
        })
        .sort(function (s1, s2) {
          // TODO 时间戳还是时间？
          if (vm.order === "time-sequential") {
            return s1.creTime >= s2.creTime ? 1 : -1;
          } else if (vm.order === "time-reverse") {
            return s1.creTime < s2.creTime ? 1 : -1;
          } else if (vm.order === "ansNum-sequential") {
            return parseInt(s1.ansNum) >= parseInt(s2.ansNum) ? 1 : -1;
          } else if (vm.order === "ansNum-reverse") {
            return parseInt(s1.ansNum) < parseInt(s2.ansNum) ? 1 : -1;
          }
        });
    },
  },
  mounted() {
    let vm = this;
    this.$http
      .get("survey/my")
      .then((res) => {
        if (res.status === 200) {
          // console.log(res.data);
          // console.log(1);
          let tempData = JSON.parse(JSON.stringify(res.data));
          tempData.forEach((s) => {
            let statuses = ["已关闭", "已开启", "未发布", "已删除"];
            s.status = statuses[s.status];
            s.creTime = vm.convertTime(s.creTime);
            s.pubTime = vm.convertTime(s.pubTime);
            s.deadline = vm.convertTime(s.deadline);
          });
          this.surveys = tempData.filter(function (s) {
            return ["已关闭", "已开启", "未发布"].includes(s.status);
          });
          console.log("publish保存的问卷列表:");
          console.log(this.surveys);
        }
      })
      .catch((err) => {
        console.log(err);
        if (err.response.status === 401) {
          localStorage.removeItem("LoginState");
          this.$router.push("/login");
        } else if (err.response.status === 500) {
          this.$message("服务器错误");
        } else {
          this.$message.error("网络错误，请稍后再试！");
        }
      });
  },
};
</script>

<style lang="less" scoped>
// .mid_layout {
//   width: 75%;
//   margin: 0 auto;
// }
// 搜索框相关样式
.search-area {
  text-align: center;
  height: 50px;
}

/deep/ .el-input__inner {
  height: 50px !important;
  font-size: 18px;
}

.search-area .el-button {
  font-size: 18px;
  height: 50px;
  width: 120px;
}

/deep/ .el-tabs__item {
  font-size: 18px !important;
}

/deep/ .el-col-12 {
  width: 25% !important;
  margin-right: 1%;
}

/* 问卷列表样式 */
.serve-list {
  width: 100%;
  height: 100%;
  text-align: left;
  font-size: 26px;
  line-height: 60px;
  font-family: "Microsoft YaHei";
  margin-top: 10px;
}

.tab_change {
  width: 380px;
}

.serve-list .el-row {
  padding-top: 20px;
}

/* 问卷卡片样式 */
.serve-item {
  width: 97%;
  background-color: #e5edf3;
  padding: 5px;
  // border: 5px solid white;
  border-radius: 10px;
  margin-top: 10px;
  margin-left: 1%;
}

/* 问卷分为上下两层的样式 */
.item-top {
  padding-left: 20px;
  height: 50px;
  overflow: hidden;
  position: relative;
}

.item-bottom {
  height: 50px;
  overflow: hidden;
  padding-left: 20px;
  margin-top: -10px;
  margin-bottom: 10px;
  position: relative;
}

/* 左上角问卷名字 */
.item-title {
  font-size: 26px;
  font-family: "Microsoft YaHei";
}

/* 右上角问卷信息 */
.item-info {
  float: right;
  font-size: 16px;
  padding-inline: 10px;
}

/* 左下角问卷操作 */
.item-left {
  float: left;
}

.item-left .el-button {
  font-size: 18px;
  padding-right: 5px;
}

/* 右下角问卷操作按钮 */
.item-right {
  float: right;
}

.item-margin {
  margin-right: 10px;
}
.item-right el-button {
  float: right;
}

.search-input {
  width: 500px;
  padding-right: 10px;
  padding-top: 10px;
}

.item-right .el-button {
  font-size: 15px;
  width: 160px;
}
</style>
